import Vue from 'vue'
import VueI18n from 'vue-i18n'
import storage from 'store'

import { setHtmlPageLang, setLoadLocalePool } from './helper'
import { localeSetting } from '/@/settings/localeSetting'
import { useLocaleStoreWithOut } from '/@/store/modules/locale'

// default lang
const localeStore = useLocaleStoreWithOut()
const locale = localeStore.getLocale

const { fallback } = localeSetting

Vue.use(VueI18n)

export const defaultLang = locale
const defaultLocal = await import(`./lang/${locale}.ts`)
const message = defaultLocal.default?.message ?? {}

const i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: defaultLang,
  legacy: false,
  fallbackLocale: fallback,
  messages: {
    [locale]: message,
  },
} as any)

/**
 * @param lang
 * @returns
 */
export function loadLanguageAsync(locale = defaultLang) {
  return new Promise((resolve) => {
    // 缓存语言设置
    storage.set('lang', locale)
    setHtmlPageLang(locale)
    setLoadLocalePool((loadLocalePool) => {
      loadLocalePool.push(locale)
    })
    return resolve(locale)
  })
}

export function i18nRender(key) {
  return i18n.t(`${key}`)
}
export default i18n
